package com.example.presentshopping.ui.custom;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


import com.example.presentshopping.R;
import com.example.presentshopping.config.base.MyApplication;
import com.example.presentshopping.config.bean.LotteryViewBean;
import com.example.presentshopping.config.bean.LuckydrawBean;
import com.example.presentshopping.mvp.presenter.PublicGetTask;
import com.example.presentshopping.net.http.HttpRequest;
import com.example.presentshopping.net.http.HttpURL;
import com.example.presentshopping.net.observer.TaskCallback;
import com.example.presentshopping.exent.LuckydrawEvent;
import com.example.presentshopping.utils.ToastUtil;
import com.example.presentshopping.utils.tool.GsonUtils;

import org.greenrobot.eventbus.EventBus;

public class LotteryView extends SurfaceView implements SurfaceHolder.Callback {


    /**
     * holder
     */
    private SurfaceHolder mHolder;


    private List<Prize> prizes;
    private boolean flags;

    private int lottery = 6; //设置中奖号码

    private int current = 2; //抽奖开始的位置

    private int count = 0; //旋转次数累计

    private int countDown; //倒计次数，快速旋转完成后，需要倒计多少次循环才停止

    private int transfer = Color.parseColor("#fee400");//中奖背景

    private int MAX = 50; //最大旋转次数

    private OnTransferWinningListener listener;
    private PublicGetTask Collectiosenter;

    public void setOnTransferWinningListener(OnTransferWinningListener listener) {
        this.listener = listener;
    }

    public interface OnTransferWinningListener {
        /**
         * 中奖回调
         *
         * @param position
         */
        void onWinning(Prize posin, int position);
    }


    /**
     * 设置中奖号码
     *
     * @param lottery
     */
    public void setLottery(int lottery) {
        if (prizes != null && Math.round(prizes.size() / 2) == 0) {
            throw new RuntimeException("开始抽奖按钮不能设置为中奖位置！");
        }
        this.lottery = lottery;
    }

    /**
     * 设置中奖颜色
     *
     * @param transfer
     */
    public void setTransfer(int transfer) {
        this.transfer = transfer;
    }

    /**
     * 设置奖品集合
     *
     * @param prizes
     */
    public void setPrizes(List<Prize> prizes) {
        this.prizes = prizes;
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        handleTouch(event);
        return super.onTouchEvent(event);
    }

    public static final int MIN_CLICK_DELAY_TIME = 1000;//这里设置不能超过多长时间
    private long lastClickTime;

    /**
     * 触摸
     *
     * @param event
     */
    public void handleTouch(MotionEvent event) {

        Point touchPoint = new Point((int) event.getX() - getLeft(), (int) event.getY());
        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                long currentTime = SystemClock.uptimeMillis();
                if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
                    try {

                        Prize prize = prizes.get(Math.round(prizes.size()) / 2);
                        //Log.e("LotteryView",""+prize);
                        if (prize.isClick(touchPoint, getMeasuredWidth())) {
                            if (!flags) {
                                Turntableaisneg(prize);
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                lastClickTime = currentTime;

                break;
            default:
                break;
        }
    }


    private class SurfaceRunnable implements Runnable {
        @Override
        public void run() {

            while (flags) {
                Canvas canvas = null;
                try {
                    canvas = mHolder.lockCanvas();

                    drawBg(canvas);

                    drawTransfer(canvas);

                    drawPrize(canvas);

                    controllerTransfer();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //涓轰簡璁╂瘡娆＄粯鍒跺浘褰㈡椂鑳藉椤哄埄杩涜锛屾渶濂藉皢瑙ｉ攣鏀惧埌寮傚父涓繘琛屽鐞嗭紝涔熷氨鏄锛屽鏋渃anvas涓嶄负绌猴紝閮藉皢鍏跺叧闂紝璁╀笅涓�娆″惊鐜兘澶熼『鍒╄繘琛岀粯鍒�
                    if (canvas != null)
                        mHolder.unlockCanvasAndPost(canvas);
                }
            }
        }
    }

    //绘制所有奖品背景
    private void drawBg(Canvas canvas) {

        canvas.drawColor(Color.WHITE, Mode.CLEAR);
        int width = getMeasuredWidth() / 3;
        int x1 = 0;
        int y1 = 0;

        int x2 = 0;
        int y2 = 0;

        int len = (int) Math.sqrt(prizes.size());

        for (int x = 0; x < len * len; x++) {

            Prize prize = prizes.get(x);

            int index = x;
            x1 = getPaddingLeft() + width * (Math.abs(index) % len);
            y1 = getPaddingTop() + width * (index / len);

            x2 = x1 + width;
            y2 = y1 + width;
            Rect rect = new Rect(x1, y1, x2, y2);

            Paint paint = new Paint();
            paint.setColor(prize.getBgColor());
            canvas.drawRect(rect, paint);
        }
    }

    //绘制旋转的奖品背景
    private void drawTransfer(Canvas canvas) {

        int width = getMeasuredWidth() / 3;
        int x1;
        int y1;

        int x2;
        int y2;
        int len = (int) Math.sqrt(prizes.size());
        current = next(current, len);
        x1 = getPaddingLeft() + width * (Math.abs(current) % len);
        y1 = getPaddingTop() + width * ((current) / len);

        x2 = x1 + width;
        y2 = y1 + width;

        Rect rect = new Rect(x1, y1, x2, y2);
        Paint paint = new Paint();
        paint.setColor(transfer);
        canvas.drawRect(rect, paint);
    }

    //控制旋转的速度
    private void controllerTransfer() {


        if (count > MAX) {
            countDown++;
            SystemClock.sleep(count * 5);
        } else {
            SystemClock.sleep(count * 2);
        }

        count++;
        if (countDown > 2) {
            if (lottery == current) {
                countDown = 0;
                count = 0;
                setStartFlags(false);
                if (listener != null) {
                    //切换到主线程中运行
                    post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onWinning(prizes.get(current), current);
                        }
                    });

                }
            }
        }
    }

    public void setStartFlags(boolean flags) {

        this.flags = flags;

    }

    //绘制奖品背景
    private void drawPrize(Canvas canvas) {

        int width = getMeasuredWidth() / 3;
        int x1 = 0;
        int y1 = 0;

        int x2 = 0;
        int y2 = 0;

        int len = (int) Math.sqrt(prizes.size());

        for (int x = 0; x < len * len; x++) {

            Prize prize = prizes.get(x);
            Log.e("drawPrize", prize.Icon + "---");
            int index = x;
            x1 = getPaddingLeft() + width * (Math.abs(index) % len);
            y1 = getPaddingTop() + width * (index / len);

            x2 = x1 + width;
            y2 = y1 + width;
            Rect rect = new Rect(x1 + width / 10, y1 + width / 10, x2 - width / 10, y2 - width / 10);
            prize.setRect(rect);
            canvas.drawBitmap(prize.getIcon(), null, rect, null);
        }
    }


    public void start() {

        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(new SurfaceRunnable());
    }

    //获取随机中奖数，实际开发中一般中奖号码是服务器告诉我们的
    private int getRandom() {
        Random r = new Random();
        int nextInt = r.nextInt(prizes.size());
        if (nextInt % (Math.round(prizes.size() / 2)) == 0) {
            //随机号码等于中间开始位置，需要继续摇随机号
            return getRandom();
        }
        return nextInt;
    }

    //下一步
    public int next(int current, int len) {
        if (current + 1 < len) {
            return ++current;
        }

        if ((current + 1) % len == 0 & current < len * len - 1) {
            return current += len;
        }

        if (current % len == 0) {
            return current -= len;
        }

        if (current < len * len) {
            return --current;
        }

        return current;
    }


    public LotteryView(Context context, AttributeSet attrs) {
        super(context, attrs);

        Collectiosenter = new PublicGetTask(MyApplication.getContext(), false);
        staata();


    }

    public LotteryView(Context context) {
        this(context, null);

        Collectiosenter = new PublicGetTask(MyApplication.getContext(), false);
        staata();


    }


    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {


        Canvas canvas = null;


        try {
            canvas = mHolder.lockCanvas();
            drawBg(canvas);
            drawPrize(canvas);

            Prize prize = prizes.get(Math.round(prizes.size() / 2));
            prize.setListener(new Prize.OnClickListener() {

                @Override
                public void click() {

                    start();

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (canvas != null)
                mHolder.unlockCanvasAndPost(canvas);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        setStartFlags(false);

    }

    /**
     * 重新测量
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = Math.min(getMeasuredWidth(), getMeasuredHeight());

        setMeasuredDimension(width, width);

    }

    public void Turntableaisneg(Prize prize) {


        Collectiosenter.netWorkRequestGet(HttpURL.Req_getTurntable, new TaskCallback() {
            @Override
            public void onSuccess(String data) {

                LotteryViewBean lotteryViewBean = GsonUtils.getGson().fromJson(data, LotteryViewBean.class);
                if (lotteryViewBean.getStatus() == 0) {
                    setLottery(8);
                } else {

                    for (int x = 0; x < prizes.size(); x++) {
                        if (prizes.get(x).getName().contains(lotteryViewBean.getName())) {
                            setLottery(x);
                        }
                    }
                }
                setStartFlags(true);
                prize.click();
            }


            @Override
            public void onFailure(Throwable e, int code, String msg, boolean isNetWorkError) {
                Log.e("Turntableaisneg", "抽奖次数不足");
                ToastUtil.showMsg("抽奖次数不足");


            }
        });
        LuckydrawEvent event = new LuckydrawEvent();
        event.setDraw(1);
        EventBus.getDefault().post(event);
    }

    public void staata() {
        Collectiosenter.netWorkRequestGet(HttpURL.Req_getTurntableList, new TaskCallback() {
            @Override
            public void onSuccess(String data) {
                LuckydrawBean luckydrawBean = GsonUtils.getGson().fromJson(data, LuckydrawBean.class);
                setPrize(MyApplication.getContext(), luckydrawBean.getData());

            }

            @Override
            public void onFailure(Throwable e, int code, String msg, boolean isNetWorkError) {

            }
        });
    }


    @SuppressLint("WrongCall")
    public void setPrize(Context context, List<LuckydrawBean.DataBean> data) {
        List<Prize> params = new ArrayList<Prize>();
        int[] prizesIcon = {
                R.mipmap.jiang1, //0
                R.mipmap.jiang2,  //1
                R.mipmap.jiang3,
                R.mipmap.jiang4,
                R.mipmap.jiang5,
                R.mipmap.jiang6,
                R.mipmap.jiang7,
                R.mipmap.jiang8,
                R.mipmap.jiang9
        };

        int js = 0;
        for (int x = 0; x < 9; x++) {
            Prize lottery = new Prize();

            if (x != 4 && x != 8) {
                js = x;
                if (js > 4) {
                    js = js - 1;
                }
                lottery.setId(data.get(js).getId());
                lottery.setName(data.get(js).getName());
                //    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), prizesIcon[x]);
                Bitmap bitmap = MyApplication.bitmapList.get(js);
                lottery.setIcon(bitmap);
                lottery.setBgColor(Color.parseColor("#FD305D"));

            } else {
                lottery.setId(100);
                lottery.setName("谢谢参与");
                Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), prizesIcon[x]);
                lottery.setIcon(bitmap);
                lottery.setBgColor(Color.parseColor("#FD305D"));
            }

            params.add(lottery);


        }


        Log.e("setPrize", "--params--" + params.size());
        setPrizes(params);

        mHolder = this.getHolder();
        mHolder.addCallback(this);
        postInvalidate();

        surfaceCreated(mHolder);
    }

}
